package com.ailot.cloud.base.security.authentication.handler;

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.ailot.cloud.base.common.dto.Result;
import com.ailot.cloud.base.common.enums.CommonCodeEnum;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 认证失败处理器
 *
 * @author litao
 */

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        Result<String> result = new Result<>(CommonCodeEnum.FALSE.getCode());
        if (e != null) {
            result.setMsg(e.getMessage());
            result.setData(e.getMessage());
        }
        httpServletResponse.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        PrintWriter printWriter = httpServletResponse.getWriter();
        printWriter.append(JSONUtil.toJsonStr(result));
        printWriter.flush();
        printWriter.close();
    }
}
